<template>
	<view class="container">
		<!-- 商品图片 -->
		<uni-swiper-dot class="uni-swiper-dot-box" :current="current" field="content">
      <swiper class="swiper-box" :current="swiperDotIndex" @change="changeSwiper">
        <swiper-item  v-for="i in carouselImages" :key="i.id">
          <view class="swiper-item" @click="clickBannerItem(item)">
            <image :src="i.imgUrl" mode="aspectFill" :draggable="false" />
          </view>
        </swiper-item>
      </swiper>
		</uni-swiper-dot>
		<!--  商品描述  -->
		<view class="introduce-section">
			<text class="title">{{proDescription.proName}}</text>
			<view class="price-box">
				<text class="price-tip">¥</text>
				<text class="price">{{proDescription.proPrice}}</text>
				<text class="m-price">¥488</text>
				<text class="coupon-tip">7折</text>
			</view>
			<view class="bot-row">
				<text>销量: 108</text>
				<text>库存: 4690</text>
				<text>浏览量: 768</text>
			</view>
		</view>

		<!--  分享 -->
		<view class="share-section" @click="share">
			<view class="share-icon">
				<text class="yticon icon-xingxing"></text>
				返
			</view>
			<text class="tit">该商品分享可领49减10红包</text>
			<text class="yticon icon-bangzhu1"></text>
			<view class="share-btn">
				立即分享
				<text class="yticon icon-you"></text>
			</view>

		</view>
		<!--  优惠卷  -->
		<view class="c-list">
			<view class="c-row b-b" @click="toggleSpec">
				<text class="tit">购买类型</text>
				<view class="con">
					<text class="selected-text" v-for="(sItem, sIndex) in specSelected" :key="sIndex">
						{{sItem.name}}
					</text>
				</view>
				<text class="yticon icon-you"></text>
			</view>
			<view class="c-row b-b">
				<text class="tit">优惠券</text>
				<text class="con t-r red">领取优惠券</text>
				<text class="yticon icon-you"></text>
			</view>
			<view class="c-row b-b">
				<text class="tit">促销活动</text>
				<view class="con-list">
					<text>新人首单送20元无门槛代金券</text>
					<text>订单满50减10</text>
					<text>订单满100减30</text>
					<text>单笔购买满两件免邮费</text>
				</view>
			</view>
			<view class="c-row b-b">
				<text class="tit">服务</text>
				<view class="bz-list con">
					<text>7天无理由退换货 ·</text>
					<text>假一赔十 ·</text>
				</view>
			</view>
		</view>

		<!-- 评价 -->
		<view class="eva-section">
			<view class="e-header">
				<text class="tit">评价</text>
				<text>(86)</text>
				<text class="tip">好评率 100%</text>
				<text class="yticon icon-you"></text>
			</view>
			<view class="eva-box">
				<image class="portrait" :src="commentData.prodAvatar" mode="aspectFill"></image>
				<view class="right" @click="proComments">
					<text class="name">{{ commentData.userName }}</text>
					<text class="con">{{ commentData.comment }}</text>
					<view class="bot">
						<text class="attr">购买参数：{{ commentData.prodParam}}</text>
						<text class="time">{{ commentData.createdAt }}</text>
					</view>
				</view>
			</view>
		</view>

		<view class="detail-desc">
			<view class="d-header">
				<text>图文详情</text>
			</view>
      <div style="width:100%">
        <view v-for="i in detailsImage" :key="i.id">
          <img style="width:100%;display:block;" :src="i.imgUrl" />
        </view>

      </div>
		</view>

		<!-- 底部操作菜单 -->
		<view class="goods-carts">
			<uni-goods-nav :options="options" :fill="true" :button-group="buttonGroup" @click="onClick"
				@buttonClick="buttonClick" />
		</view>


		<!-- 规格-模态层弹窗 -->
		<view class="popup spec" :class="specClass" @touchmove.stop.prevent="stopPrevent" @click="toggleSpec">
			<!-- 遮罩层 -->
			<view class="mask"></view>
			<view class="layer attr-content" @click.stop="stopPrevent">
				<view class="a-t">
					<image :src="proDescription.image"></image>
					<view class="right">
						<text class="price">¥ {{proDescription.proPrice}}</text>
						<text class="stock"></text>
						<view class="selected">
							已选：
							<text class="selected-text" v-for="(sItem, sIndex) in specSelected" :key="sIndex">
								{{sItem.name}}
							</text>
              <text> {{numberValue}}个</text>
						</view>
					</view>
				</view>
      <!-- 已选商品-->
				<view v-for="(item,index) in prodArgs" :key="index" class="attr-list">
					<text>{{item.name}}</text>
					<view class="item-list">
						<text v-for="(childItem, childIndex) in item.children"
							:key="childIndex" class="tit" :class="{selected: childItem.selected}"
							@click="selectSpec(childItem.id, item.id)">
							{{childItem.name}}
						</text>
					</view>
				</view>
        <text>数量</text>
        <uni-section title="">
          <uni-number-box :min="1" :value="numberValue" @change="change" />
        </uni-section>
        <button class="btn" @click="toggleSpec">完成</button>
			</view>
		</view>
	</view>
</template>

<script>
import {
  findImage,
  findProd, getArgs
} from "../../../api/product/details";
  import UniRow from "../../../uni_modules/uni-row/components/uni-row/uni-row";
  import UniCol from "../../../uni_modules/uni-row/components/uni-col/uni-col";
  import {addCart, listCart} from "../../../api/cart/cart";
  import {getInfo} from "../../../api/login";
  import {comments} from '@/api/product/product';
	export default {
		components: {UniCol, UniRow},
		data() {
			return {
        comments: [],
        commentData: '',
        //商铺编号
        shops_id: null,
        //商品编号
        proId:null,
				// 商品详情页底部栏数据begin
        cartNumber:0,
				options: [{
					icon: 'chat',
					text: '客服'
				}, {
					icon: 'shop',
					text: '店铺',
					info: 2,
					infoBackgroundColor: '#007aff',
					infoColor: "#f5f5f5"
				}, {
					icon: 'cart',
					text: '购物车',
					info: 0
				}],
				buttonGroup: [{
						text: '加入购物车',
						backgroundColor: 'linear-gradient(90deg, #FFCD1E, #FF8A18)',
						color: '#fff'
					},
					{
						text: '立即购买',
						backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
						color: '#fff'
					}
				],
				customButtonGroup: [{
						text: '加入购物车',
						backgroundColor: 'linear-gradient(90deg, #1E83FF, #0053B8)',
						color: '#fff'
					},
					{
						text: '立即购买',
						backgroundColor: 'linear-gradient(90deg, #60F3FF, #088FEB)',
						color: '#fff'
					}
				],
				customButtonGroup1: [{
					text: '立即购买',
					backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
					color: '#fff'
				}],
        //轮播图
        carouselImages: [],
        //详情图
        detailsImage:[],
				// 商品详情页底部栏数据end
				proDescription: [],
        numberValue: 1,
				current: 0,
				swiperDotIndex: 0,
				specClass: 'none',
				specSelected: [],
        argStatus: false,

				favorite: true,
				shareList: [],
        prodArgs:[],
        //已选父级
				specList: [{
						id: 1,
						name: '尺寸',
					},
					{
						id: 2,
						name: '颜色',
					},
				],

				specChildList: [{
						id: 1,
						pid: 1,
						name: 'XS',
					},
					{
						id: 2,
						pid: 1,
						name: 'S',
					},
					{
						id: 3,
						pid: 1,
						name: 'M',
					},
					{
						id: 4,
						pid: 1,
						name: 'L',
					},
					{
						id: 5,
						pid: 1,
						name: 'XL',
					},
					{
						id: 6,
						pid: 1,
						name: 'XXL',
					},
					{
						id: 7,
						pid: 2,
						name: '白色',
					},
					{
						id: 8,
						pid: 2,
						name: '珊瑚粉',
					},
					{
						id: 9,
						pid: 2,
						name: '草木绿',
					},
				]
			};
		},
    created(){
      this.loadData();
    },

		async onLoad(options) {
      this.proId=options.proId
      let proDescription =  await findProd(options.proId)
      this.proDescription=proDescription.data
      this.shops_id = proDescription.data.shopId
      this.loadCartNumber();
      //查找轮播图和详情图
      let images =  await findImage(options.proId)
      images.data.forEach((i)=>{
        if (i.imgType === "0") {
          this.carouselImages.push(i)
        }else if (i.imgType === "1") {
          this.detailsImage.push(i)
        }
      })

      let a = await getArgs(options.proId)
      this.prodArgs = this.handleTree(a.data,"id","parentId","children")

      //规格 默认选中第一条
			this.prodArgs.forEach(item => {
        item.children.forEach((cItem, index)=>{
          if (index===0) {
            this.$set(cItem, 'selected', true);
            this.specSelected.push(cItem);
          }
        })
			})
			// this.shareList = await this.$api.json('shareList');


		},

		methods: {
      async loadData(){
        this.comments = await comments();
        this.commentData = this.comments.rows[0];
      },
      //商品数量
      change(value) {
        this.numberValue = value
      },
      //商品评论
      proComments(){
        uni.navigateTo({
          url: '/pages/product/comments/index'
        }); // 可以返回到上一级页面，不会跳转到首页，也就是从哪里跳来，就返回到哪里去
        // this.$tab.redirectTo('/pages/product/comments/index')
      },

      onClick(e){
        if (e.index === 0) {
          /* this.$tab.redirectTo(`/pages/order/createOrder?proId=`+this.proId)*/
          console.info("客服")
        } else if (e.index === 1) {
          uni.navigateTo({
            url: '/pages/mine/shop/self_shop/index?shopId=' + this.proDescription.shopId
          }); // 可以返回到上一级页面，不会跳转到首页，也就是从哪里跳来，就返回到哪里去
          // this.$tab.redirectTo('/pages/mine/shop/self_shop/index?shopId=' + this.proDescription.shopId);
          /*this.$tab.redirectTo(`/pages/order/createOrder?proId=` + this.proId);*/
        } else {
          console.info("购物车")
          this.$tab.switchTab(`/pages/cart/cart/index`);
        }
      },

      async buttonClick(e){
        //0加入购物车/1立即购买
        if (e.index === 0) {
          this.toggleSpec()
          //获取用户ID
          let userInfo = await getInfo()
          let userId = userInfo.user.userId
          //商铺ID
          let shopsId = this.shops_id
          //商品ID
          let productId = this.proId
          //商品数量
          let productCount = this.numberValue
          let cartList = await listCart(userId);
          for (let i = 0; i < cartList.rows.length; i++) {
            if (productId==cartList.rows[i].productId){
              return;
            }
          }
          await addCart({
            userId,
            shopsId,
            productId,
            productCount
          })
          this.loadCartNumber()
        } else {
          uni.navigateTo({
            url: `/pages/order/createOrder?proId=${this.proId}&numberValue=${this.numberValue}`
          }); // 可以返回到上一级页面，不会跳转到首页，也就是从哪里跳来，就返回到哪里去
          // this.$tab.redirectTo(`/pages/order/createOrder?proId=`+this.proId)
        }
      },

      async loadCartNumber(){
        let userInfo = await getInfo()
        let userId = userInfo.user.userId
        let query = {}
        query.userId = userId
        let list = await listCart(query);
        this.options[2].info = list.total
      },

			clickBannerItem(item) {
				console.info(item)
			},
			changeSwiper(e) {
				this.current = e.detail.current
			},
			//规格弹窗开关
			toggleSpec() {
				if (this.specClass === 'show') {
					this.specClass = 'hide';
					setTimeout(() => {
						this.specClass = 'none';
					}, 250);
				} else if (this.specClass === 'none') {
					this.specClass = 'show';
				}
			},
			//选择规格
			selectSpec(id, pid) {
        this.argStatus = !this.argStatus
				let list = this.prodArgs;
				list.forEach(item => {
          if (item.id === pid) {
            item.children.forEach(child=>{
              this.$set(child, 'selected', false);
              if (child.id === id && this.argStatus) {
                this.$set(child, 'selected', true);
              }

            })
          }
				})
				// 存储已选择
				/**
				 * 修复选择规格存储错误
				 * 将这几行代码替换即可
				 * 选择的规格存放在specSelected中
				 */
				this.specSelected = [];
				list.forEach(item => {
              item.children.forEach(child=>{
                if (child.selected === true) {
                  this.specSelected.push(child);
                }
              })
				})
			},
			//分享
			share() {
				this.$refs.share.toggleMask();
			},
			//收藏
			toFavorite() {
				this.favorite = !this.favorite;
			},
			buy() {
				uni.navigateTo({
					url: `/pages/order/createOrder`
				})
			},
			stopPrevent() {},

      handleTree(data, id, parentId, children) {
        let config = {
          id: id || 'id',
          parentId: parentId || 'parentId',
          childrenList: children || 'children'
        };

        var childrenListMap = {};
        var nodeIds = {};
        var tree = [];

        for (let d of data) {
          let parentId = d[config.parentId];
          if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
          }
          nodeIds[d[config.id]] = d;
          childrenListMap[parentId].push(d);
        }

        for (let d of data) {
          let parentId = d[config.parentId];
          if (nodeIds[parentId] == null) {
            tree.push(d);
          }
        }

        for (let t of tree) {
          adaptToChildrenList(t);
        }

        function adaptToChildrenList(o) {
          if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
          }
          if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
              adaptToChildrenList(c);
            }
          }
        }

        return tree;
      }
		},

	}
</script>

<style lang='scss'>
.count{
  display: inline-block;
}
	.swiper-item {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #fff;
		height: 750rpx;
		line-height: 300rpx;
	}

	.swiper-box {
		height: 350px;
	}

	@media screen and (min-width: 500px) {
		.uni-swiper-dot-box {
			width: 400px;
			/* #ifndef APP-NVUE */
			margin: 0 auto;
			/* #endif */
			margin-top: 8px;
		}

		.image {
			width: 100%;
		}
	}

	page {
		background: $page-color-base;
		padding-bottom: 160upx;
	}

	.icon-you {
		font-size: $font-base + 2upx;
		color: #888;
	}

	.carousel {
		height: 722upx;
		position: relative;

		swiper {
			height: 100%;
		}

		.image-wrapper {
			width: 100%;
			height: 100%;
		}

		.swiper-item {
			display: flex;
			justify-content: center;
			align-content: center;
			height: 750upx;
			overflow: hidden;

			image {
				width: 100%;
				height: 100%;
			}
		}

	}

	/* 标题简介 */
	.introduce-section {
		background: #fff;
		padding: 20upx 30upx;

		.title {
			font-size: 32upx;
			color: $font-color-dark;
			height: 50upx;
			line-height: 50upx;
		}

		.price-box {
			display: flex;
			align-items: baseline;
			height: 64upx;
			padding: 10upx 0;
			font-size: 26upx;
			color: $uni-color-primary;
		}

		.price {
			font-size: $font-lg + 2upx;
		}

		.m-price {
			margin: 0 12upx;
			color: $font-color-light;
			text-decoration: line-through;
		}

		.coupon-tip {
			align-items: center;
			padding: 4upx 10upx;
			background: $uni-color-primary;
			font-size: $font-sm;
			color: #fff;
			border-radius: 6upx;
			line-height: 1;
			transform: translateY(-4upx);
		}

		.bot-row {
			display: flex;
			align-items: center;
			height: 50upx;
			font-size: $font-sm;
			color: $font-color-light;

			text {
				flex: 1;
			}
		}
	}

	/* 分享 */
	.share-section {
		display: flex;
		align-items: center;
		color: $font-color-base;
		background: linear-gradient(left, #fdf5f6, #fbebf6);
		padding: 12upx 30upx;

		.share-icon {
			display: flex;
			align-items: center;
			width: 70upx;
			height: 30upx;
			line-height: 1;
			border: 1px solid $uni-color-primary;
			border-radius: 4upx;
			position: relative;
			overflow: hidden;
			font-size: 22upx;
			color: $uni-color-primary;

			&:after {
				content: '';
				width: 50upx;
				height: 50upx;
				border-radius: 50%;
				left: -20upx;
				top: -12upx;
				position: absolute;
				background: $uni-color-primary;
			}
		}

		.icon-xingxing {
			position: relative;
			z-index: 1;
			font-size: 24upx;
			margin-left: 2upx;
			margin-right: 10upx;
			color: #fff;
			line-height: 1;
		}

		.tit {
			font-size: $font-base;
			margin-left: 10upx;
		}

		.icon-bangzhu1 {
			padding: 10upx;
			font-size: 30upx;
			line-height: 1;
		}

		.share-btn {
			flex: 1;
			text-align: right;
			font-size: $font-sm;
			color: $uni-color-primary;
		}

		.icon-you {
			font-size: $font-sm;
			margin-left: 4upx;
			color: $uni-color-primary;
		}
	}

	.c-list {
		font-size: $font-sm + 2upx;
		color: $font-color-base;
		background: #fff;

		.c-row {
			display: flex;
			align-items: center;
			padding: 20upx 30upx;
			position: relative;
		}

		.tit {
			width: 140upx;
		}

		.con {
			flex: 1;
			color: $font-color-dark;

			.selected-text {
				margin-right: 10upx;
			}
		}

		.bz-list {
			height: 40upx;
			font-size: $font-sm+2upx;
			color: $font-color-dark;

			text {
				display: inline-block;
				margin-right: 30upx;
			}
		}

		.con-list {
			flex: 1;
			display: flex;
			flex-direction: column;
			color: $font-color-dark;
			line-height: 40upx;
		}

		.red {
			color: $uni-color-primary;
		}
	}

	/* 评价 */
	.eva-section {
		display: flex;
		flex-direction: column;
		padding: 20upx 30upx;
		background: #fff;
		margin-top: 16upx;

		.e-header {
			display: flex;
			align-items: center;
			height: 70upx;
      weight: 100%px;
			font-size: $font-sm + 2upx;
			color: $font-color-light;

			.tit {
				font-size: $font-base + 2upx;
				color: $font-color-dark;
				margin-right: 4upx;
			}

			.tip {
				flex: 1;
				text-align: right;
			}

			.icon-you {
				margin-left: 10upx;
			}
		}
	}

	.eva-box {
		display: flex;
		padding: 20upx 0;

		.portrait {
			flex-shrink: 0;
			width: 80upx;
			height: 80upx;
			border-radius: 100px;
		}

		.right {
			flex: 1;
			display: flex;
			flex-direction: column;
			font-size: $font-base;
			color: $font-color-base;
			padding-left: 26upx;

			.con {
				font-size: $font-base;
				color: $font-color-dark;
				padding: 20upx 0;
			}

			.bot {
				display: flex;
				justify-content: space-between;
				font-size: $font-sm;
				color: $font-color-light;
			}
		}
	}

	/*  详情 */
	.detail-desc {
		background: #fff;
		margin-top: 16upx;

		.d-header {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 80upx;
			font-size: $font-base + 2upx;
			color: $font-color-dark;
			position: relative;

			text {
				padding: 0 20upx;
				background: #fff;
				position: relative;
				z-index: 1;
			}

			&:after {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translateX(-50%);
				width: 300upx;
				height: 0;
				content: '';
				border-bottom: 1px solid #ccc;
			}
		}
	}

	/* 规格选择弹窗 */
	.attr-content {
		padding: 10upx 30upx;

		.a-t {
			display: flex;

			image {
				width: 170upx;
				height: 170upx;
				flex-shrink: 0;
				margin-top: -40upx;
				border-radius: 8upx;
				;
			}

			.right {
				display: flex;
				flex-direction: column;
				padding-left: 24upx;
				font-size: $font-sm + 2upx;
				color: $font-color-base;
				line-height: 42upx;

				.price {
					font-size: $font-lg;
					color: $uni-color-primary;
					margin-bottom: 10upx;
				}

				.selected-text {
					margin-right: 10upx;
				}
			}
		}

		.attr-list {
			display: flex;
			flex-direction: column;
			font-size: $font-base + 2upx;
			color: $font-color-base;
			padding-top: 30upx;
			padding-left: 10upx;
		}

		.item-list {
			padding: 20upx 0 0;
			display: flex;
			flex-wrap: wrap;

			text {
				display: flex;
				align-items: center;
				justify-content: center;
				background: #eee;
				margin-right: 20upx;
				margin-bottom: 20upx;
				border-radius: 100upx;
				min-width: 60upx;
				height: 60upx;
				padding: 0 20upx;
				font-size: $font-base;
				color: $font-color-dark;
			}

			.selected {
				background: #fbebee;
				color: $uni-color-primary;
			}
		}
	}

	/*  弹出层 */
	.popup {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 99;

		&.show {
			display: block;

			.mask {
				animation: showPopup 0.2s linear both;
			}

			.layer {
				animation: showLayer 0.2s linear both;
			}
		}

		&.hide {
			.mask {
				animation: hidePopup 0.2s linear both;
			}

			.layer {
				animation: hideLayer 0.2s linear both;
			}
		}

		&.none {
			display: none;
		}

		.mask {
			position: fixed;
			top: 0;
			width: 100%;
			height: 100%;
			z-index: 1;
			background-color: rgba(0, 0, 0, 0.4);
		}

		.layer {
			position: fixed;
			z-index: 99;
			bottom: 0;
			width: 100%;
			min-height: 40vh;
			border-radius: 10upx 10upx 0 0;
			background-color: #fff;

			.btn {
				height: 66upx;
				line-height: 66upx;
				border-radius: 100upx;
				background: $uni-color-primary;
				font-size: $font-base + 2upx;
				color: #fff;
				margin: 30upx auto 20upx;
			}
		}

		@keyframes showPopup {
			0% {
				opacity: 0;
			}

			100% {
				opacity: 1;
			}
		}

		@keyframes hidePopup {
			0% {
				opacity: 1;
			}

			100% {
				opacity: 0;
			}
		}

		@keyframes showLayer {
			0% {
				transform: translateY(120%);
			}

			100% {
				transform: translateY(0%);
			}
		}

		@keyframes hideLayer {
			0% {
				transform: translateY(0);
			}

			100% {
				transform: translateY(120%);
			}
		}
	}

	/* 底部操作菜单 */
	.example-body {
		padding: 0;
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
	}

	.goods-carts {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		position: fixed;
		left: 0;
		right: 0;
		/* #ifdef H5 */
		left: var(--window-left);
		right: var(--window-right);
		/* #endif */
		bottom: 0;
	}
</style>